package tool

import (
	"fmt"
	"reflect"
	"service/model/mod"
	"strconv"
	"time"

	"gitee.com/cloudapex/ulern/util"
)

/*
 * 描述: 商家ID的有序队列
 *
 *******************************************************************/
type QTBillNo struct {
	BillNo int64 // 单号的计数器
	At     int64 // 数据的时间点
}

func (this *QTBillNo) RKey() string {
	return "TQBillNo"
}

func (this *QTBillNo) RDb() mod.ERDB {
	return mod.ERDB_Permt
}

func (this *QTBillNo) ToMap() map[string]interface{} {
	m := make(map[string]interface{})
	elem := reflect.ValueOf(this).Elem()
	relType := elem.Type()
	for i := 0; i < relType.NumField(); i++ {
		m[relType.Field(i).Name] = elem.Field(i).Interface()
	}
	return m
}

func (this *QTBillNo) HMSet() error {

	//mod.RDB(mod.ERDB_Permt).Hash.HSet(this.RKey(), this.ToMap())
	for k, v := range this.ToMap() {
		reply := mod.RDB(mod.ERDB_Permt).Hash.HSet(this.RKey(), k, v, true)
		if reply.Error() != nil {
			return reply.Error()
		}
	}
	return nil
	//return Ur(this.RDb()).HMSet(this.RKey(), this.ToMap()).Err()
}

/*
 * 描述: 获取本次TQ通话的单号
 *
 ******************************************************************/
func (this *QTBillNo) GetBillNo() (string, error) {
	//mss, err := Ur(this.RDb()).HGetAll(this.RKey()).Result()

	ms, err := mod.RDB(this.RDb()).Hash.HGetAll(this.RKey()).Result()

	if err == nil {

		mss, ok := ms.(map[string]string)
		if !ok {
			return "", nil
		}

		this.BillNo, _ = strconv.ParseInt(mss["BillNo"], 10, 64)
		this.At, _ = strconv.ParseInt(mss["At"], 10, 64)
		if !util.IsToday(this.At) {
			this.At = time.Now().Unix()
			this.BillNo = 0
			if err := this.HMSet(); err != nil {
				return "", err
			}
		}

		if err := mod.RDB(this.RDb()).Hash.HIncrBy(this.RKey(), "BillNo", 1).Error(); err != nil {
			return "", err
		}

		str := util.TimeToString(this.At)
		return fmt.Sprintf("TQ%s%.5d", str, this.BillNo+1), err
	}
	return "", err
}
